
package de.gwtprime.server.servlets;

import java.io.IOException;
import java.security.Principal;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.gwtprime.server.model.User2;
import de.gwtprime.server.sql.helper.HibernateHelper;
import de.gwtprime.server.util.LoginHelper;


/**
 * Callback function from the google authentication
 * @author jan
 *
 */
@SuppressWarnings("serial") 
public class LoginGoogleCallbackServlet extends HttpServlet {
	private static Logger log = Logger.getLogger(LoginGoogleCallbackServlet.class.getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Principal googleUser = request.getUserPrincipal();
		
		if (googleUser != null) {
			log.info("Successful login with google user: " +googleUser.getName());
			
	
			// Lookup user in DB
			User2 user = User2.findUserByEmail(googleUser.getName());
			
			// if the user does not exist in the DB -> create new one
			// and save it to DB
			if(user==null){
				
				log.info("No user found in the DB -> Creating user with email: "+googleUser.getName());
				user = new User2();
				user.setEmail(googleUser.getName());
				user.setName("benutzer"+(int)(Math.random()*1000000));
				HibernateHelper.persist(user);
			}
			
			// Save the user to the session
			request.getSession().setAttribute("user", user);
		}

		// Attach the last location to the new url -> call page, the user was on before login
		response.sendRedirect(LoginHelper.getApplitionURL(request)+request.getSession().getAttribute("lastPage"));

	}
}
